package com.xnyzc.lhy.didi.service.impl.invoice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.didi.entity.param.invoice.CancelInvoiceParam;
import com.xnyzc.lhy.didi.entity.param.invoice.InvoiceApplyForParam;
import com.xnyzc.lhy.didi.entity.param.invoice.InvoiceQueryParam;
import com.xnyzc.lhy.didi.entity.param.invoice.ResendInvoiceParam;
import com.xnyzc.lhy.didi.entity.results.invoice.InvoiceQueryResults;
import com.xnyzc.lhy.didi.feign.Invoice.IOaSysInvoiceApplyService;
import com.xnyzc.lhy.didi.mapper.invoice.OaSysInvoiceDidiApplyMapper;
import com.xnyzc.lhy.didi.service.invoice.InvoiceService;
import com.xnyzc.lhy.finance.entity.invoice.OaSysInvoiceDidiApply;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceApplyResult;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceInvalidResult;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceQueryResult;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceQuerySuccessResponse;
import com.xnyzc.lhy.finance.entity.invoice.response.InvoiceResendResult;
import com.xnyzc.lhy.finance.entity.params.invoice.InvoiceApplyForDiDiParam;
import com.xnyzc.lhy.finance.entity.params.invoice.InvoiceInvalidDiDiParam;
import com.xnyzc.lhy.finance.entity.params.invoice.InvoiceQueryDiDiParam;
import com.xnyzc.lhy.finance.entity.params.invoice.ResendInvoiceDiDiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 发票相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-10-08
 */
@Slf4j
@Service
public class InvoiceServiceImpl implements InvoiceService {
    @Autowired
    IOaSysInvoiceApplyService iOaSysInvoiceApplyService;

    @Autowired
    OaSysInvoiceDidiApplyMapper oaSysInvoiceDidiApplyMapper;

    /**
     * 发票申请
     *
     * @return
     */
    @Override
    public DiDiRv getInvoiceApplyFor(InvoiceApplyForParam param) {
        if (StringUtils.isBlank(param.getInvoice_title()) || StringUtils.isBlank(param.getInvoice_id())
                || CheckUtil.objIsEmpty(param.getInvoice_order_ids(), param.getInvoice_amount())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }

        // 查询发票是否已开具
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysInvoiceDidiApply.BLUE_INVOICE_ID, param.getInvoice_id());
        int oaSysInvoiceDidiApplyCount = oaSysInvoiceDidiApplyMapper.selectCount(queryWrapper);
        if (oaSysInvoiceDidiApplyCount > 0) {
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        }

        //初始化开发票服务参数
        InvoiceApplyForDiDiParam invoiceApplyForDiDiParam = this.convertiInvoiceApplyForDiDiParam(param);

        //调用百望云开发票服务
        // InvoiceApplyResult invoiceApplyResult = iOaSysInvoiceApplyService.getInvoiceApplyForDiDi(invoiceApplyForDiDiParam);

        // 调用AA开发票服务
        InvoiceApplyResult invoiceApplyResult = iOaSysInvoiceApplyService.getInvoiceAaApplyForDiDi(invoiceApplyForDiDiParam);


        if (invoiceApplyResult.getIsSuccess() == true) {
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        } else {
            log.error(String.format("开发票失败：{}",
                    invoiceApplyResult.getInvoiceErrorResponse() != null
                            ? invoiceApplyResult.getInvoiceErrorResponse().getErrmsg()
                            : EDiDiErrorCode.unKnow.getDesc()));
            return DiDiRv.wrapError(EDiDiErrorCode.openInvoiceError);
        }
    }

    /**
     * 发票查询
     *
     * @return
     */
    @Override
    public DiDiRv getInvoiceQuery(InvoiceQueryParam param) {
        InvoiceQueryResults results = new InvoiceQueryResults();
        if (StringUtils.isBlank(param.getInvoice_id())) {
            return DiDiRv.wrap(EDiDiErrorCode.parameterError, results);
        }

        //初始化开发票服务参数
        InvoiceQueryDiDiParam invoiceQueryDiDiParam = this.convertiInvoiceQueryDiDiParam(param);

        //调用百望云开发票服务
        // InvoiceQueryResult invoiceQueryResult = iOaSysInvoiceApplyService.getInvoiceQueryDiDi(invoiceQueryDiDiParam);

        // 调用AA开发票服务
        InvoiceQueryResult invoiceQueryResult = iOaSysInvoiceApplyService.getInvoiceAaQueryDiDi(invoiceQueryDiDiParam);

        if (invoiceQueryResult.getIsSuccess() == true) {
            InvoiceQuerySuccessResponse invoiceQuerySuccessResponse = invoiceQueryResult.getInvoiceQuerySuccessResponse();

            results.setCheck_code(invoiceQuerySuccessResponse.getInvoiceCheckCode());
            results.setInvoice_code(invoiceQuerySuccessResponse.getInvoiceCode());
            results.setInvoice_number(invoiceQuerySuccessResponse.getInvoiceNo());
            results.setPdf_url(invoiceQuerySuccessResponse.getFileUrl());
            results.setStatus(invoiceQuerySuccessResponse.getStatus());
            results.setStatus_message(invoiceQuerySuccessResponse.getStatusMessage());

            return DiDiRv.wrap(EDiDiErrorCode.success, results);
        } else {
            log.error("发票编号：{},发票查询失败：{}", param.getInvoice_id(), invoiceQueryResult.getInvoiceErrorResponse() != null
                    ? invoiceQueryResult.getInvoiceErrorResponse().getErrmsg()
                    : EDiDiErrorCode.unKnow.getDesc());
            return DiDiRv.wrapError(EDiDiErrorCode.queryInvoiceError);
        }
    }

    /**
     * 重发发票
     *
     * @return
     */
    @Override
    public DiDiRv getResendInvoice(ResendInvoiceParam param) {
        if (StringUtils.isBlank(param.getInvoice_id())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }

        //初始化发票重发服务参数
        ResendInvoiceDiDiParam resendInvoiceDiDiParam = this.convertiResendInvoiceParam(param);

        //调用开发票服务
        InvoiceResendResult invoiceResendResult = iOaSysInvoiceApplyService.getResendInvoiceDiDi(resendInvoiceDiDiParam);

        if (invoiceResendResult.getIsSuccess() == true) {
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        } else {
            log.error(String.format("重发发票失败：{0}",
                    invoiceResendResult.getInvoiceErrorResponse() != null
                            ? invoiceResendResult.getInvoiceErrorResponse().getErrmsg()
                            : EDiDiErrorCode.unKnow.getDesc()));
            return DiDiRv.wrapError(EDiDiErrorCode.resendInvoiceError);
        }
    }

    /**
     * 发票作废
     *
     * @param cancelInvoiceParam
     * @return
     */
    @Override
    public DiDiRv getInvoiceInvalidDiDi(CancelInvoiceParam cancelInvoiceParam) {
        if (CheckUtil.strIsEmpty(cancelInvoiceParam.getBlue_invoice_id())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }

        // 查询发票是否已作废
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysInvoiceDidiApply.RED_INVOICE_ID, cancelInvoiceParam.getRed_invoice_id());
        int oaSysInvoiceDidiApplyCount = oaSysInvoiceDidiApplyMapper.selectCount(queryWrapper);
        if (oaSysInvoiceDidiApplyCount > 0) {
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        }

        InvoiceInvalidDiDiParam invoiceInvalidDiDiParam = new InvoiceInvalidDiDiParam();
        invoiceInvalidDiDiParam.setAppId(cancelInvoiceParam.getApp_id());
        invoiceInvalidDiDiParam.setBlueInvoiceId(cancelInvoiceParam.getBlue_invoice_id());
        invoiceInvalidDiDiParam.setRedInvoiceId(cancelInvoiceParam.getRed_invoice_id());
        // 百望云发票服务
        // InvoiceInvalidResult invoiceInvalidDiDi = iOaSysInvoiceApplyService.getInvoiceInvalidDiDi(invoiceInvalidDiDiParam);
        // AA发票服务
        InvoiceInvalidResult invoiceInvalidDiDi = iOaSysInvoiceApplyService.getInvoiceAaInvalidDiDi(invoiceInvalidDiDiParam);

        if (invoiceInvalidDiDi != null && invoiceInvalidDiDi.getIsSuccess() == true) {
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        } else {
            log.error(String.format("发票作废失败：{0}",
                    invoiceInvalidDiDi.getInvoiceErrorResponse() != null
                            ? invoiceInvalidDiDi.getInvoiceErrorResponse().getErrmsg()
                            : EDiDiErrorCode.unKnow.getDesc()));
            return DiDiRv.wrapError(EDiDiErrorCode.cancelInvoiceError);
        }
    }

    /**
     * 创建发票服务参数
     *
     * @param invoiceApplyForParam didi发票参数
     * @return
     */
    private InvoiceApplyForDiDiParam convertiInvoiceApplyForDiDiParam(InvoiceApplyForParam invoiceApplyForParam) {
        InvoiceApplyForDiDiParam invoiceApplyForDiDiParam = new InvoiceApplyForDiDiParam();
        /**
         * 滴滴订单id
         */
        invoiceApplyForDiDiParam.setOpenOid(invoiceApplyForParam.getOpen_oid());
        /**
         * 滴滴用户id
         */
        invoiceApplyForDiDiParam.setOpenPid(invoiceApplyForParam.getOpen_pid());

        /**
         * 时间戳
         */
        invoiceApplyForDiDiParam.setTimestamp(invoiceApplyForParam.getTimestamp());

        /**
         * 验签
         */
        invoiceApplyForDiDiParam.setSign(invoiceApplyForParam.getSign());

        /**
         * 标识
         */
        invoiceApplyForDiDiParam.setAppId(invoiceApplyForParam.getApp_id());

        /**
         * 滴滴方唯一发票编号
         */
        invoiceApplyForDiDiParam.setInvoiceId(invoiceApplyForParam.getInvoice_id());

        /**
         * 发票抬头
         */
        invoiceApplyForDiDiParam.setInvoiceTitle(invoiceApplyForParam.getInvoice_title());

        /**
         * 金额
         */
        invoiceApplyForDiDiParam.setInvoiceAmount(invoiceApplyForParam.getInvoice_amount());

        /**
         * 开票类型 1个人2公司
         */
        invoiceApplyForDiDiParam.setInvoiceType(invoiceApplyForParam.getInvoice_type());

        /**
         * 开票同程订单号, 逗号分隔
         */
        invoiceApplyForDiDiParam.setInvoiceOrderIds(invoiceApplyForParam.getInvoice_order_ids());

        /**
         * 用户邮箱地址
         */
        invoiceApplyForDiDiParam.setEmail(invoiceApplyForParam.getEmail());

        /**
         * 纳税人识别号
         */
        invoiceApplyForDiDiParam.setCustomerIdentifier(invoiceApplyForParam.getCustomer_identifier());

        /**
         * 开票银行
         */
        invoiceApplyForDiDiParam.setBankName(invoiceApplyForParam.getBank_name());

        /**
         * 银行账户
         */
        invoiceApplyForDiDiParam.setBankAccount(invoiceApplyForParam.getBank_account());

        /**
         * 注册地址
         */
        invoiceApplyForDiDiParam.setRegisteAddress(invoiceApplyForParam.getRegiste_address());

        /**
         * 发票备注
         */
        invoiceApplyForDiDiParam.setInvoiceRemark(invoiceApplyForParam.getInvoice_remark());

        /**
         * 注册手机号
         */
        invoiceApplyForDiDiParam.setRegistePhone(invoiceApplyForParam.getRegiste_phone());

        return invoiceApplyForDiDiParam;
    }

    /**
     * 创建发票查询服务参数
     *
     * @param param
     * @return
     */
    private InvoiceQueryDiDiParam convertiInvoiceQueryDiDiParam(InvoiceQueryParam param) {
        InvoiceQueryDiDiParam invoiceQueryDiDiParam = new InvoiceQueryDiDiParam();

        /**
         * Didi发票唯一编号
         */
        invoiceQueryDiDiParam.setInvoiceId(param.getInvoice_id());

        return invoiceQueryDiDiParam;
    }

    /**
     * 创建发票重发服务参数
     *
     * @param param
     * @return
     */
    private ResendInvoiceDiDiParam convertiResendInvoiceParam(ResendInvoiceParam param) {
        ResendInvoiceDiDiParam resendInvoiceDiDiParam = new ResendInvoiceDiDiParam();
        resendInvoiceDiDiParam.setInvoiceId(param.getInvoice_id());
        resendInvoiceDiDiParam.setEmail(param.getEmail());
        return resendInvoiceDiDiParam;
    }
}
